package bingo.des;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
/**
 * Dec 8, 2008 12:46:55 PM DESHelper.java
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:可逆的数据加密和解密的实现
 * ChangeLog:
 */
public class DESHelper {
	/**
	 * 默认的密钥
	 */
	private String secretKey;
	/**
	 * 加密密码
	 */
	private Cipher encryptCipher;
	/**
	 * 解密密码
	 */
	private Cipher decryptCipher;
	
	
	/**
	 * 随机字符范围
	 */
	private static final byte[] RANDOM_BYTES = {
		'1','2','3','4','5','6','7','8',
		'9','0',
		'a','b','c','d','e','f','g','h',
		'i','j','k','l','m',
		'n','o','p','q','r','s','t','u',
		'v','w','x','y','z'
	};


	/**
	 * 不指定密钥构造方法
	 * 
	 * @throws Exception
	 */
	public DESHelper() {
		this(null);
	}
	/**
	 * 指定密钥构造方法
	 * 
	 * @param secretKey 指定的密钥
	 * @throws Exception
	 */
	public DESHelper(String secretKey) {
		this.secretKey = secretKey;
		Key key = genernateKey(secretKey);

		try {
			encryptCipher = Cipher.getInstance("DES");
			encryptCipher.init(Cipher.ENCRYPT_MODE, key);

			decryptCipher = Cipher.getInstance("DES");
			decryptCipher.init(Cipher.DECRYPT_MODE, key);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 加密字符串
	 * 
	 * @param plaintext 明文字符串
	 * @return 加密后的字符串
	 * @throws Exception
	 */
	public String encrypt(String plaintext) throws Exception {
		return byteArr2HexStr(encrypt(plaintext.getBytes()));
	}


	/**
	 * 解密字符串
	 * 
	 * @param cryptograph
	 *            需解密的字符串
	 * @return 解密后的字符串
	 * @throws Exception
	 */
	public String decrypt(String cryptograph) throws Exception {
		return new String(decrypt(hexStr2ByteArr(cryptograph)));
	}

	/**
	 * 解密字符串
	 * @param secretKey 密钥
	 * @param cryptograph
	 *            需解密的字符串
	 * @return 解密后的字符串
	 * @throws Exception
	 */
	public String decrypt(String secretKey ,String cryptograph) throws Exception {
		Cipher decryptCipher = Cipher.getInstance("DES");
		Key key = new javax.crypto.spec.SecretKeySpec(secretKey.getBytes(), "DES");
		decryptCipher.init(Cipher.DECRYPT_MODE, key);
		return new String(decryptCipher.doFinal(hexStr2ByteArr(cryptograph)));
	}


	public String getKey(){
		return this.secretKey;
	}

	/**
	 * 将byte数组转换为表示16进制值的字符串， 如：byte[]{8,18}转换为：0813, 
	 * 和 public byte[] hexStr2ByteArr(String srcString) 互为可逆的转换过程
	 * 
	 * @param srcArray 需要转换的byte数组
	 * @return 转换后的字符串
	 * @throws Exception
	 */
	private String byteArr2HexStr(byte[] srcArray) throws Exception {
		int iLen = srcArray.length;
		// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = srcArray[i];
			// 把负数转换为正数
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			// 小于0F的数需要在前面补0
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}

	/**
	 * 将表示16进制值的字符串转换为byte数组, 
	 * 和public static String byteArr2HexStr(byte[] srcArray)互为可逆的转换过程
	 * @param srcString 需要转换的字符串
	 * @return 转换后的byte数组
	 * @throws Exception
	 */
	private byte[] hexStr2ByteArr(String srcString) throws Exception {
		byte[] arrB = srcString.getBytes();
		int iLen = arrB.length;
		// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}




	/**
	 * 产生随机密钥
	 * @return 密钥
	 */
	private Key genernateKey(String secretKey){
		byte[] keyArray = new byte[8];
		
		int randomCharLength = RANDOM_BYTES.length;
		SecureRandom random = new SecureRandom();
		if(secretKey != null){
			byte[] secretKeyBytes = secretKey.getBytes();
			for(int i = 0; i < 8; i++){
				keyArray[i] = i < secretKeyBytes.length ? secretKeyBytes [i] : RANDOM_BYTES[random.nextInt(randomCharLength)];
			}
		}else{
			for(int i = 0; i < 8; i++){
				keyArray[i] = RANDOM_BYTES[random.nextInt(randomCharLength)];
			}
		}
		this.secretKey = new String(keyArray);
		return new javax.crypto.spec.SecretKeySpec(keyArray, "DES");
	}


	/**
	 * 加密字节数组
	 * 
	 * @param arrB
	 *            需加密的字节数组
	 * @return 加密后的字节数组
	 * @throws Exception
	 */
	private byte[] encrypt(byte[] arrB) throws Exception {
		return encryptCipher.doFinal(arrB);
	}



	/**
	 * 解密字节数组
	 * 
	 * @param arrB
	 *            需解密的字节数组
	 * @return 解密后的字节数组
	 * @throws Exception
	 */
	private byte[] decrypt(byte[] arrB) throws Exception {
		return decryptCipher.doFinal(arrB);
	}
}

